﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using static CoreApi.common.Constant;

namespace FileApi.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class FileController : ControllerBase
    {
        [HttpGet]
        public string Gethhh()
        {
            return "hhh";
        }
        /// <summary>
        /// 上传文件
        /// </summary>
        [HttpPost]
        public ResponseView UploadFile(IFormFile file)
        {
            ResponseView view = new ResponseView();
            try
            {
                var fileExtension = Path.GetExtension(file.FileName);

                //判断后缀是否是图片
                const string fileFilt = ".gif|.jpg|.jpeg|.png|.xlsx|.xls|.doc|.docx|.zip|.rar|.7z|.mp3|.mp4";
                if (fileExtension == null)
                {
                    view.code = 400;
                    view.msg = "上传的文件没有后缀";
                    return view;
                }

                if (fileFilt.IndexOf(fileExtension.ToLower(), StringComparison.Ordinal) <= -1)
                {
                    view.code = 400;
                    view.msg = "请上传jpg、png、gif、mp3、mp4格式的文件";
                    return view;
                }

                // 限制文件大小
                if (file.Length > ((10 * 1024) * 1024))
                {
                    view.code = 500;
                    view.msg = "文件大小不能超过10M";
                    return view;
                }

                var name = file.FileName;

                string url = "D:/upload/附件/";

                string url2 = DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + "/" + DateTime.Now.ToString("dd") + "/";
                string path = url + url2;

                // 是否存在文件夹
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                var fileStream = System.IO.File.Create(Path.Combine(path, name));

                file.OpenReadStream().CopyTo(fileStream);

                // 释放文件流
                file.OpenReadStream().Dispose();

                fileStream.Close();

                view.data = url2 + name;

                return view;
            }
            catch (Exception ex)
            {
                view.code = 500;
                view.msg = ex.Message.ToString();
                return view;
            }
        }
    }
}
